package com.wangzd.community.controller;

import com.wangzd.community.dto.AccessTokenDTO;
import com.wangzd.community.dto.GiteeUser;
import com.wangzd.community.model.User;
import com.wangzd.community.provider.GiteeProvider;
import com.wangzd.community.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author wangzd
 * @create 2021-08-18 14:06
 */
@Controller
@Slf4j
public class AuthorizeController {

    @Autowired
    GiteeProvider giteeProvider;

    @Autowired
    private UserService userService;

    //从yaml文件获取
    @Value("${gitee.clientid}")
    private String clientId;
    @Value("${gitee.clientsecret}")
    private String clientSecret;
    @Value("${gitee.redirecturi}")
    private String redirectUri;


    //获得授权码code
    @GetMapping("/callback")
    public String callback(@RequestParam(name="code") String code,
                           @RequestParam(name="state") String state,
                           HttpServletResponse response){
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setCode(code);
        accessTokenDTO.setClient_id(clientId);
        accessTokenDTO.setClient_secret(clientSecret);
        accessTokenDTO.setRedirect_uri(redirectUri);
        accessTokenDTO.setState(state);
        accessTokenDTO.setGrant_type("authorization_code");
        //获取令牌
        String accessToken = giteeProvider.getAccessToken(accessTokenDTO);
        //通过令牌获取用户信息
        GiteeUser giteeUser = giteeProvider.getUser(accessToken);
        //保存到数据库
        if (giteeUser != null && giteeUser.getId() != null){
            User user = new User();
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            user.setName(giteeUser.getName());
            user.setAccountId(String.valueOf(giteeUser.getId()));
            user.setAvatarUrl(giteeUser.getAvatarUrl());
            userService.createOrUpdate(user);
            response.addCookie(new Cookie("token",token));
            return "redirect:/";
            //登录成功
        }else{
            log.error("callback get github error,{}",giteeUser);
            //登录失败
            return "redirect:/";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request,
                         HttpServletResponse response){
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }
}
